package com.wuye.service;

import com.wuye.model.*;
import com.wuye.web.AppConfig;
import com.wuye.web.Constant;
import com.wuye.web.MenuType;
import org.json.JSONObject;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.*;

import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.apache.commons.logging.*;

import java.math.BigDecimal;
import java.util.*;
import java.io.*;

import com.wuye.repository.*;
import org.tuckey.web.filters.urlrewrite.utils.StringUtils;

@Service
public class MenuService {
    private Log log = LogFactory.getLog(this.getClass());
    @Autowired
    private MenuScheduleRepository menuSchedule;
    @Autowired
    private MenuActivityRepository menuActivityRepository;
    @Autowired
    private MenuRepository menuRepository;
    @Autowired
    private AppConfig appConfig;
    public List<Menu> findAllMenuSale() throws RuntimeException {
        List<Menu> menus = menuRepository.findAllOnSale();
        return menus;
    }

    public List<Object[]> findAllMenuDetail() throws RuntimeException {
        List<Object[]> menus = menuRepository.findAllByItemNameDesc();
        return menus;
    }

    public int sumAllMenu(String itemTypes, String itemName) {
        int pageSize = 10;
        int total = 0;
        if (StringUtils.isBlank(itemName)) {
            if (StringUtils.isBlank(itemTypes) || itemTypes.equals("1")) {
                total = menuRepository.sumss();
            } else {
                String itemType = "";
                for (MenuType me : MenuType.values()) {
                    if (me.getMenuType().equals(itemTypes)) {
                        itemType = me.toString();
                    }
                }

                total = menuRepository.sums(itemType);
            }
        } else {
            if (StringUtils.isBlank(itemTypes) || itemTypes.equals("1")) {
                total = menuRepository.sumssbyItems("%" + itemName + "%");
            } else {
                String itemType = "";
                for (MenuType me : MenuType.values()) {
                    if (me.getMenuType().equals(itemTypes)) {
                        itemType = me.toString();
                        break;
                    }
                }

                total = menuRepository.sumsa(itemName, itemType);
            }
        }
        if (total * 1.0 / pageSize == 0.0) {
            return total / pageSize;
        } else {
            return total / pageSize + 1;
        }
    }

    public MenuDetail findOneMenu(String menuId) {
        List<Object[]> obj = menuRepository.findOneDetail(menuId);
        List<MenuDetail> de = convertList(obj);
        return de.get(0);
    }

    public void updateMenu(Menu menu,String storeNum) {
        Menu menus = menuRepository.findOne(menu.getMenuId());
        if (menu.getImageFile() != null) menus.setImageFile(menu.getImageFile());
        if (menu.getItemName() != null) menus.setItemName(menu.getItemName());
        if (menu.getItemPrice() != null) menus.setItemPrice(menu.getItemPrice());
        if (menu.getItemDescription() != null) menus.setItemDescription(menu.getItemDescription());
        if (menu.getItemType() != null) menus.setItemType(menu.getItemType());
        if (menu.getItemUnit() != null) menus.setItemUnit(menu.getItemUnit());
        MenuActivity mm = menuActivityRepository.findOne(menu.getMenuId());
        mm.setStoreNum(Integer.valueOf(storeNum));
        menuActivityRepository.save(mm);
        menuRepository.save(menus);
    }

    //下架操作
    public void updateMenuStatus(String menuId) {
        MenuActivity menus = menuActivityRepository.findByMenuId(menuId);
        menus.setForSale(0);
        menuActivityRepository.save(menus);
    }

    //上架操作
    public void updateMenuStatus2(String menuId) {
        MenuActivity menus = menuActivityRepository.findByMenuId(menuId);
        menus.setForSale(1);
        menuActivityRepository.save(menus);
    }

    public List<Object[]> queryAllsByItemType(String types) {
        List<Object[]> lists = menuRepository.findMenus(types);
        return lists;
    }


    //删除菜品
    public void deleteMenuss(String menuId) {
        menuRepository.delete(menuId);
    }

    //查询所有品类
    public List<String> findItemType() {
        List<String> str = new ArrayList<String>();
        for (MenuType menus : MenuType.values()) {
            str.add(menus.getMenuType());
        }
        return str;
    }

    //查询所有菜品
    //根据菜品名称和菜品品类分类查询
    @Transactional(rollbackFor = {Exception.class})
    public List<Object[]> queryAllByMenunameDivide(String itemNames, String itemTypes, String curPage) {
        int pageSize = 10;
        if (StringUtils.isBlank(curPage)) curPage = "1";
        int beginSize = (Integer.parseInt(curPage) - 1) * pageSize;
        int endSize = pageSize;
        String itemName = itemNames;
        if ("1".equals(itemTypes) && StringUtils.isBlank(itemNames))
            return menuRepository.findAllOrderByItemTypesDesc(beginSize, endSize);
        String itemType = "";
        for (MenuType me : MenuType.values()) {
            if (me.getMenuType().equals(itemTypes)) {
                itemType = me.toString();
                break;
            }
        }
        if (StringUtils.isBlank(itemName) && StringUtils.isBlank(itemType)) {
            return menuRepository.findAllOrderByItemTypesDesc(beginSize, endSize);
        } else if (StringUtils.isBlank(itemName)) {
            return menuRepository.findByItemTypeOrderByItemTypesDesc(itemType, beginSize, endSize);
        } else if (StringUtils.isBlank(itemType) || "1".equals(itemTypes)) {

            return menuRepository.findItemNameOrderByItemTypeDesc("%" + itemName + "%");
        } else {
            return menuRepository.findByItemNameAndItemTypeOrderByItemTypesDesc("%" + itemName + "%", itemType, beginSize, endSize);
        }
    }
    //修改库存数量
    public void storeCount(String menuId,String nums){
        MenuActivity mm = menuActivityRepository.findOne(menuId);
        mm.setStoreNum(Integer.valueOf(nums));
        menuActivityRepository.save(mm);
    }

    @Transactional(rollbackFor = {Exception.class})
    public List<MenuDetail> convertList(List<Object[]> obj){
        List<MenuDetail> datails = new ArrayList<MenuDetail>();
       if(obj.size()>=1){
            for (Object[] ob : obj) {
                MenuDetail de = new MenuDetail();
                de.setMenuId((String) ob[0]);
                de.setImageFile((String) ob[1]);
                de.setItemName((String) ob[2]);
                if(ob[3]==null){
                    de.setItemDescription("材料新鲜，质量保证");
                }else {
                    de.setItemDescription((String) ob[3]);
                }
                de.setItemType(MenuType.valueOf((String) ob[4]).getMenuType());
                if(ob[5]==null) {
                    de.setItemUnit("份");
                }else{
                    de.setItemUnit((String) ob[5]);
                }
                if(ob[6]==null) {
                    de.setItemPrice(0.00f);
                }else{
                    de.setItemPrice(Float.valueOf(ob[6].toString()));
                }
                de.setIsUping(Integer.valueOf(ob[7].toString()));
                if(ob[8]==null){
                    de.setStoreNum(0);
                }else{
                    de.setStoreNum(Integer.valueOf(ob[8].toString()));
                }
                datails.add(de);
            }
        }
        return datails;
    }

    //增加菜品
    public void addMenu(Menu menu,String storeNum){
        Date now = new Date();
        String r = String.valueOf(System.nanoTime());
        String orderSn = Constant.sdfNumber2.format(now) + r.substring(r.length() - 3);
        menu.setMenuId(orderSn);
        menuActivityRepository.save(new MenuActivity(orderSn,1,Integer.valueOf(storeNum)));
        String aa = "";
        for(MenuType p:MenuType.values()){
            if(p.getMenuType().equals(menu.getItemType())){
                aa = p.toString();
                break;
            }
        }
        menu.setItemType(aa);
        menuRepository.save(menu);
    }



//提取订餐时间
    public JSONObject orderTimes(){
        String path = appConfig.getImagePath()+"/sendTime.txt";
        File file = new File(path);
        if(!file.exists()){
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        StringBuilder sb = new StringBuilder();
        FileReader input = null;
        try {
            input = new FileReader(file);
            char[] bt = new char[10];
            int length = 0;
            while((length=input.read(bt))!=-1){
                for(int i = 0;i<length;i++){
                    sb.append(bt[i]);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(input !=null) {
                try {
                    input.close();
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
        }
        if(sb==null || sb.equals("") || sb.length()<=1) sb = new StringBuilder("13:00:0016:30:00");
        String s1 = sb.substring(0,8);
        String s2 = sb.substring(8);
        JSONObject json = new JSONObject();
        json.put("s1",s1);
        json.put("s2",s2);
        return json;
    }


    //查询当天已完成的订单

}